package com.dagit.test.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.dagit.network.Instance;
import com.dagit.network.traffic.IMessage;
import com.dagit.network.traffic.Message;
class kos implements Runnable{
	private Socket socket;
	kos(Socket socket){
		this.socket = socket;
	}
	@Override
	public void run() {
		try {
			ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
			Message<Object> msg  = (Message<Object>)input.readObject();
			System.out.println(msg.getInput());
			@SuppressWarnings("unchecked")
			IMessage<Object, Object> ret = (IMessage<Object, Object>) Class.forName(msg.getClazz()).newInstance();
			Object res = ret.processMessage(msg.getInput());
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			out.writeObject(res);
			System.out.println("socket closed");
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
	}
}
public class Server {
	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(8050);
		while(true){
			Socket socket = server.accept();
			new Thread(new kos(socket)).start();
		}

		
	}
}
